import axios from "axios";
import { Message } from "element-ui";

/**
 *
 * @param {*} config axios配置
 * @param {*} customConfig 外部配置
 * @param {*} loadingConfig loading配置
 */
export function request(
  config,
  customConfig,
  loadingConfig = { content: "loading", duration: 0 }
) {
  // 配置新建一个 axios 实例
  const service = axios.create({
    baseURL: import.meta.env.VITE_API_URL,
    timeout: 20000,
    headers: { "Content-Type": "application/json" },
  });

  // 合并外部配置与自定义默认配置
  let customOptions = {
    ...customConfig,
  };

  // 添加请求拦截器
  service.interceptors.request.use(
    (config) => {
      return config;
    },
    (error) => {
      // 对请求错误做些什么
      return Promise.reject(error);
    }
  );

  // 添加响应拦截器
  service.interceptors.response.use(
    (response) => {
      const { code, msg } = response.data;
      if (code !== 200) {
        Message.error(msg);
      } else {
        const requestType = response.config.method.toLowerCase()
        const successMsg = msg || customOptions.msg
        const { showSuccessMsg } = customOptions
        if (['put', 'delete'].includes(requestType)) {
          Message.success(successMsg)
        } else {
          if (showSuccessMsg && successMsg) {
            Message.success(successMsg);
          }
        }
        return response.data;
      }
    },
    (error) => {
      Message.error("请求服务异常，请刷新后重试");
      return Promise.reject(error);
    }
  );

  return service(config);
}